const axios = require('axios');
const { req } = require('./axios'); // 注意这里导入的是 req 方法
const { reqImage } = require('./axios'); // 注意这里导入的是 req 方法
const { reqGet } = require('./axios'); // 注意这里导入的是 req 方法
const fs = require('fs');
const path = require('path');
const BaseURL = "https://pro.admin.jianpiao.net/api/login";



//登录接口
async function login() {
    try {
        let data = {
            "password": "W3sw@UK3XKmLcofY",
            "roleId": 0,
            "username": "黎雷仪"
        };

        let res = await req({ url: BaseURL, data: data, method: 'POST' }); // 注意这里调用的是 req 方法
        // console.log('登录成功', res.data.token);
        saveToken(res.data.token)
        // 这里如何保存Token到本地
        return res.data.token;
    } catch (err) {
        console.log('登录失败', err);
        return err;
    }
}


// 保存 Token 到本地
function saveToken(token) {
    const tokenData = JSON.stringify({ token });
    fs.writeFileSync('token.json', tokenData);
}


// 从本地读取 Token
function readToken() {
    try {
        const tokenData = fs.readFileSync('token.json');
        const { token } = JSON.parse(tokenData);
        return token;
    } catch (err) {
        console.error('读取 Token 出错', err);
        return null;
    }
}



//获取登录码
async function getLoginQrCode(code) {
    //这里如何读取本地的Token
    const token = readToken();
    console.log('本地的Token', token);
    try {
        let url = `https://pro.admin.jianpiao.net/api/clients/${code}/loginCode`
        let res = await req({ url: url, method: 'GET', headers: { 'Authorization': `Bearer ${token}` } });
        console.log('登录码', res.data);
        return res.data
    } catch (err) {
        console.log('注销码', err);
        return err;
    }

}


//获取注销码
async function getLogoutQrCode(code) {
    //这里如何读取本地的Token
    const token = readToken();
    console.log('本地的Token', token);
    try {
        let url = `https://pro.admin.jianpiao.net/api/clients/${code}/logoutCode`
        let res = await req({ url: url, method: 'GET', headers: { 'Authorization': `Bearer ${token}` } });
        console.log('登录码', res.data);
        return res.data
    } catch (err) {
        console.log('注销码', err);
        return err;
    }

}

/**
 *  内容生成二维码
 * @param {*} data 
 * @returns 
 */
async function generateQRCode(data) {
    try {


        const localFilePath = path.join(__dirname, 'qrcode2.jpg');

        // 检查是否存在文件
        if (fs.existsSync(localFilePath)) {
            // 如果存在，先删除文件
            fs.unlinkSync(localFilePath);
            console.log('Existing file deleted:', localFilePath);
        }

        const url = `https://api.pwmqr.com/qrcode/create/?url=${encodeURIComponent(data)}`
        // 示例用法
        let config = {
            method: 'get',
            maxBodyLength: Infinity,
            url: url,
            headers: {
                'Cookie': 'BEC=db8a1d31b2a4d64810501fb1837bc0e1'
            }
        };

        const response = await reqImage(config)

        console.log('localFilePath', localFilePath);
        await fs.promises.writeFile(localFilePath, response.data, 'binary');
        console.log('Image file saved to', localFilePath);
        return localFilePath;  // Return the file path

    } catch (error) {
        console.error('Request error:', error.message);
        throw error; // Re-throw the error to maintain the rejection in the async function
    }
}


/**
 * 
 * @param {影院Code 8位} cinemaCode 
 */
async function getTicketInfo(code, index) {

    console.log('获取影院信息请求参数', `code:=${code}---index${index}`);
    // const url = 'https://pro.admin.jianpiao.net/api/clients?cinemaCode=${code}'
    const url = `https://pro.admin.jianpiao.net/api/clients?cinemaName=${code}&pageNum=${1}&pageSize=${5}`
    try {
        // 示例用法
        let config = {
            url: url,
            headers: { 'Authorization': `Bearer ${readToken()}` }
        };
        let res = await reqGet(config);

        console.log('影院返回数据', `res.data:=${res.list}`);
        const indexValue = parseInt(index) - 1;
        if (indexValue >= 0 && indexValue < res.data.list.length) {
            console.log('firstObject', `indexValue:=${indexValue}`);
            const firstObject = res.data.list[indexValue];
            // 使用 firstObject 进行后续操作
            console.log('firstObject', `firstObject:=${firstObject.name}`);
            return firstObject
        } else {
            console.error('索引超出范围');
            return '索引超出范围';
        }
    } catch (err) {
        console.log('登录失败', err);
        return err;
    }

}


/**
 * 
 * @param {影院Code 8位} cinemaCode 
 */
async function getTicketVersion(cinemaCode, clientId) {

    console.log('获取版本号信息', `clientId:=${clientId}`);
    const url = `https://pro.admin.jianpiao.net/api/clients/versions/extensions?clientId=${clientId}`
    try {
        // 示例用法
        let config = {
            url: url,
            headers: { 'Authorization': `Bearer ${readToken()}` }
        };
        let res = await reqGet(config);

        console.log('获取版本号信息', `res.data:=${res.data}`);


        let info = `影院(${cinemaCode})当前版本是：\n`;
        for (let i = 0; i < res.data.length; i++) {
            info += res.data[i].version + "(" + res.data[i].motherboardType + ")\n";
        }

        console.log('info', `info:=${info}`);

        // if (indexValue >= 0 && indexValue < res.data.list.length) {
        //     console.log('firstObject', `indexValue:=${indexValue}`);
        //     const firstObject = res.data.list[indexValue];
        //     // 使用 firstObject 进行后续操作
        //     console.log('firstObject', `firstObject:=${firstObject.name}`);
        //     return firstObject
        // } else {
        //     console.error('索引超出范围');
        //     return '索引超出范围';
        // }
        return info
    } catch (err) {
        console.log('登录失败', err);
        return err;
    }

}


/**
 * 
 * 获取配置信息
 * @param {影院Code 8位} cinemaCode 
 */
async function getTicketConfig(clientId) {

    console.log('检票机配置', `clientId:=${clientId}`);
    const url = `https://pro.admin.jianpiao.net/api/clients/${clientId}/config`
    try {
        // 示例用法
        let config = {
            url: url,
            headers: { 'Authorization': `Bearer ${readToken()}` }
        };
        let res = await reqGet(config);

        console.log('检票机配置', `res.data:=${JSON.stringify(res.data, null, 2)}`);

        let info = `开检配置->：\n\n`;

        info += "前置时间：" + res.data.check.beforeMinute + "分钟\n后置时间：" + res.data.check.afterMinute + "\n"
            + "检票间隔：" + res.data.check.repeatCheckInterval + "分钟\n检票次数：" + res.data.check.checkLimitThreshold + "\n\n"
            + `基础配置->：\n\n` + "测试模式：" + res.data.testMode + "\n" + "是否是主设备：" + res.data.isMain + "\n" + "是否显示排期："
            + res.data.panel.showFilmSchedule + "\n" + "是否开启员工码：" + res.data.enableStaffCodeMessage + "\n\n"
            + "音量配置->\n\n" + "视频音量：" + res.data.volume.video + "\n" + "广播音量：" + res.data.volume.broadcast + "\n" + "检票音量：" + res.data.volume.check
            + "\n" + "系统音量：" + res.data.volume.system

        console.log('info', `info:=${info}`);

        return info
    } catch (err) {
        console.log('登录失败', err);
        return err;
    }

}

/**
 * 
 * 获取配置信息
 * @param {cinemaId} cinemaId 
 */
async function getCheckConfig(cinemaId) {

    console.log('检票方式', `clientId:=${cinemaId}`);
    const url = `https://pro.admin.jianpiao.net/api/cinemas/${cinemaId}/check-platform-config`
    try {
        // 示例用法
        let config = {
            url: url,
            headers: { 'Authorization': `Bearer ${readToken()}` }
        };
        let res = await reqGet(config);

        console.log('检票方式', `res.data:=${JSON.stringify(res.data, null, 2)}`);

        let info = `验票信息：↓\n\n`;
        info += "检票方式：" + res.data.platform + "\n"
            + "检票配置信息:" + JSON.stringify(res.data.config, null, 2)

        console.log('info', `info:=${info}`);

        return info
    } catch (err) {
        console.log('登录失败', err);
        return err;
    }

}


/**
 * 获取影院信息
 * @returns 
 */
async function getCinemas(cinemaId) {

    console.log('检票方式', `clientId:=${cinemaId}`);
    const url = `https://pro.admin.jianpiao.net/api/cinemas?name=&gbCode=${cinemaId}&audit=&deliveryStat`
    try {
        // 示例用法
        let config = {
            url: url,
            headers: { 'Authorization': `Bearer ${readToken()}` }
        };
        let res = await reqGet(config);

        console.log('检票方式', `res.data:=${JSON.stringify(res.data, null, 2)}`);

        let id = res.data.list[0].id
        let name = res.data.list[0].name

        console.log('id', `id:=${id}`);
        console.log('name', `name:=${name}`);
        //如何返回 id + name
        return [id, name];
    } catch (err) {
        console.log('登录失败', err);
        return err;
    }
}



/**
 * 获取角色信息
 */
async function getAdminInfo(id, name) {
    const url = `https://pro.admin.jianpiao.net/api/ctrl-admins/18`;

    try {
        // 示例用法
        let config = {
            url: url,
            headers: { 'Authorization': `Bearer ${readToken()}` }
        };
        let res = await reqGet(config);

        // 获取到的角色信息
        let data = res.data;

        // 添加新的数据到 cinemaList
        if (!data.cinemaList) {
            data.cinemaList = [];
        }

        // 检查是否已包含指定的 id
        const idExists = data.cinemaList.some(cinema => cinema.id === id);

        if (idExists) {
            return "已绑定,请勿重复添加"
        }


        data.cinemaList.push({
            "id": id,
            "name": name
        });



        let clnemaList = data.cinemaList


        console.log(clnemaList);


        const jsonObject = {
            id: "18",
            cellphone: "13023278389",
            name: "黎雷仪",
            advertiserId: "2",
            roles: [1],
            cinemaIds: []
        };


        clnemaList.forEach(element => {
            jsonObject.cinemaIds.push(element.id)
        });

        console.log(JSON.stringify(jsonObject, null, 2));

        // console.log('新角色数据', `newData:=${newData}`);

        const newUrl = `https://pro.admin.jianpiao.net/api/ctrl-admins`;

        let putConfig = {
            url: newUrl,
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${readToken()}`,
                'Content-Type': 'application/json'
            },
            data: jsonObject
        };

        let putRes = await req(putConfig);
        console.log('修改返回数据', `newData:=${putRes.message}`);
        // console.log('修改返回数据', `newData:=${JSON.stringify(putRes.data, null, 2)}`);
        return putRes.message;
    } catch (err) {
        console.log('获取角色信息失败', err);
        return err;
    }
}


// /**
//  * 
//  */
// async function updateAdmin() {
//     const url = `https://pro.admin.jianpiao.net/api/ctrl-admins`

//     try {
//         let data = {
//             "password": "W3sw@UK3XKmLcofY",
//             "roleId": 0,
//             "username": "黎雷仪"
//         };

//         let res = await req({ url: BaseURL, data: data, method: 'POST' }); // 注意这里调用的是 req 方法
//         // console.log('登录成功', res.data.token);
//         saveToken(res.data.token)
//         // 这里如何保存Token到本地
//         return res.data.token;
//     } catch (err) {
//         console.log('登录失败', err);
//         return err;
//     }

// }



module.exports = {
    login,
    getLoginQrCode,
    generateQRCode,
    getTicketInfo,
    getLogoutQrCode,
    getTicketVersion,
    getTicketConfig,
    getCheckConfig,
    getCinemas,
    getAdminInfo
};
